<!--
 * @Author: jingjingzheng 1742420988@qq.com
 * @Date: 2023-12-05 14:18:07
 * @LastEditors: jingjingzheng 1742420988@qq.com
 * @LastEditTime: 2023-12-30 23:05:12
 * @FilePath: \mdbj-ui\src\views\datamanager\road\addPanel.vue
 * @Description: 这是默认设置,请设置`customMade`, 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
-->
<template>
  <div class="app-container">
    <el-col :span="24" class="title-row">
      <span :style="{ color: theme }">| 新增道路单线</span>
    </el-col>
    <el-form id="elForm" ref="elForm" :model="formData" :rules="rules" size="medium" label-width="92px">
      <el-row>
        <el-col :span="formcolwidth">
            <el-form-item label="道路名称" label-width="120px" prop="name">
              <el-input
                v-model="formData.name"
                :disabled="false"
                clearable
                :style="{ width: '100%' }"
              ></el-input>
            </el-form-item>
        </el-col>
        <el-col :span="formcolwidth">
          <el-form-item label="保洁公司" label-width="120px" prop="cleancompany">
            <el-select
              v-model="formData.cleancompany"
              :disabled="false"
              placeholder="请选择保洁公司"
              clearable
              :style="{ width: '100%' }"
              >
              <el-option
              v-for="dict in dict.type.sys_cleancompany"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
              ></el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="formcolwidth">
          <el-form-item label="道路等级" label-width="120px" prop="roadclass_js">
            <el-select
                v-model="formData.roadclass_js"
                placeholder="请选择道路等级"
                clearable
                :style="{ width: '100%' }"
              >
                <el-option
                v-for="dict in dict.type.sys_roadclass_js"
                :key="dict.value"
                :label="dict.label"
                :value="dict.value"
              ></el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="formcolwidth">
            <el-form-item label="参考长度(m)" label-width="120px" prop="ref_length">
              <el-input
                v-model="formData.ref_length"
                :disabled="false"
                clearable
                :style="{ width: '100%' }"
                @input="formData.ref_length= formData.ref_length.replace(/[^\d|\.]/g, '')"
              ></el-input>
            </el-form-item>
        </el-col>
        <el-col :span="formcolwidth">
            <el-form-item label="机动车道宽度(m)" label-width="120px" prop="width">
              <el-input
                v-model="formData.width"
                :disabled="false"
                clearable
                :style="{ width: '100%' }"
                @input="formData.width= formData.width.replace(/[^\d|\.]/g, '')"
              ></el-input>
            </el-form-item>
        </el-col>
        <el-col :span="formcolwidth">
          <el-form-item label="机动车道数量" label-width="120px" prop="lanenumber">
            <el-input
              v-model="formData.lanenumber"
              :disabled="false"
              clearable
              :style="{ width: '100%' }"
            ></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="formcolwidth">
          <el-form-item label="非机动车道数量" label-width="120px" prop="feijdcds">
            <el-input
              v-model="formData.feijdcds"
              :disabled="false"
              clearable
              :style="{ width: '100%' }"
            ></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="formcolwidth">
          <el-form-item label="是否有人行道" label-width="120px" prop="sfsidewalk">
            <el-select
              v-model="formData.sfsidewalk"
              placeholder="请选择是否有人行道"
              clearable
              :style="{ width: '100%' }"
            >
              <el-option
                v-for="dict in dict.type.sys_sfsidewalk"
                :key="dict.value"
                :label="dict.label"
                :value="dict.value"
              ></el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="formcolwidth">
          <el-tooltip class="item" effect="dark" content="根据道路走向由西向东，由南向北，偏西或偏南为起点" placement="top">
            <el-form-item label="起点" label-width="120px" prop="startpoint">
              <el-input
                v-model="formData.startpoint"
                :disabled="false"
                clearable
                :style="{ width: '100%' }"
              ></el-input>
            </el-form-item>
          </el-tooltip>
        </el-col>
        <el-col :span="formcolwidth">
            <el-form-item label="止点" label-width="120px" prop="endpoint">
              <el-input
                v-model="formData.endpoint"
                :disabled="false"
                clearable
                :style="{ width: '100%' }"
              ></el-input>
            </el-form-item>
        </el-col>
        <el-col :span="formcolwidth">
          <el-form-item label="路面材料" label-width="120px" prop="pavementmaterials">
            <el-select
              v-model="formData.pavementmaterials"
              placeholder="请选择路面材料"
              clearable
              :style="{ width: '100%' }"
              >
              <el-option
                v-for="dict in dict.type.sys_pavementmaterials"             
                :key="dict.value"
                :label="dict.label"
                :value="dict.value"
              ></el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="formcolwidth">
          <el-form-item label="管理单位" label-width="120px" prop="managementunit">
            <el-input
              v-model="formData.managementunit"
              :disabled="false"
              clearable
              :style="{ width: '100%' }"
            ></el-input>
          </el-form-item>
      </el-col>
        <el-col :span="formcolwidth">
            <el-form-item label="备注" label-width="120px" prop="note">
              <el-input
                v-model="formData.note"
                :disabled="false"
                clearable
                :style="{ width: '100%' }"
              ></el-input>
            </el-form-item>
        </el-col>
      </el-row>
        <el-form-item class="footer" size="large">
          <el-button type="primary" @click="submitForm" icon="el-icon-check">提交</el-button>
          <el-button @click="resetForm">重置</el-button>
          <el-button type="primary" plain icon="el-icon-circle-close" @click="cancel">返回</el-button>
        </el-form-item>
    </el-form>
  </div>
</template>

<script>
import Graphic from "@arcgis/core/Graphic";
import GraphicsLayer from "@arcgis/core/layers/GraphicsLayer";
import Sketch from "@arcgis/core/widgets/Sketch";
import { v4 as uuidv4 } from "uuid";
export default {
  components: {
    Graphic,
    GraphicsLayer,
    Sketch,
  },
  props: {
    paramObj: { default: () => { } },
    mapview: { default: () => { } },
  },
  inject: ["toggleComponent"],
  dicts: [
    "sys_roadclass_js",
    "sys_cleancompany",
    "sys_sfsidewalk",
    "sys_pavementmaterials",
    "road_data_status",
  ],
  computed: {
    theme() {
      return this.$store.state.settings.theme;
    },
  },
  data() {
    return {
      // 必须给formData对象的属性设置对应空值，否则重置后无法输入数据
      formData: {
        objectid: "",
        code: "",
        name: "",
        roadnumber: "",
        roadclass_js: "",
        ref_length: "",
        length: "",
        width: "",
        pavementmaterials: "",
        note: "",
        startpoint: "",
        endpoint: "",
        oldname: "",
        cleancompany: "",
        lanenumber:"",
        feijdcds:"",
        sfsidewalk:"",
        managementunit:"",
        data_status:"",
      },
      rules: {
          name: [
            { required: true, message: '请输入道路名称', trigger: 'blur' },
          ],
          roadclass_js: [
            { required: true, message: '请选择道路等级', trigger: 'blur' },
          ],
          pavementmaterials: [
            { required: true, message: '请选择路面材料', trigger: 'change' }
          ],
          cleancompany: [
            { required: true, message: '请选择保洁单位', trigger: 'change' }
          ],
          lanenumber:[
            {required: true, "pattern": /^[0-9]*$/,"message": "只能输入正整数"}
          ],
          feijdcds:[
            {required: true, "pattern": /^[0-9]*$/,"message": "只能输入正整数"}
          ],
          sfsidewalk: [
            { required: true, message: '请选择是或否', trigger: 'change' }
          ],
          startpoint: [
            { required: true, message: '请输入道路起点名称', trigger: 'blur' },
          ],
          endpoint: [
            { required: true, message: '请输入道路止点名称', trigger: 'blur' },
          ],
          managementunit: [
            { required: false, message: '请输入管理单位全称', trigger: 'blur' },
          ],
        },
      // rules: undefined,
      featureLayer: undefined,
      // 列表宽度
      formcolwidth: 12,
      // 当前页面田加空间位置信息
      selectedGraphic: undefined,
      udpateGraphicsLayer: undefined,
      sketch: undefined,
      addGraphics: [],
    }
  },
  activated() {
    let _self = this
    console.log(_self.paramObj)
    _self.featureLayer = _self.paramObj.featureLayer;
    // 显示图形编辑面板
    _self.addGeometry();
  },
  deactivated() {
    let _self = this
    _self.clearGraphics();
    _self.clearData();
  },
  methods: {
    submitForm() {
      let _self = this;
      _self.$refs["elForm"].validate((valid) => {
        if (!valid) return;
        if (_self.selectedGraphic == undefined) {
          _self.$message.error("请添加空间位置信息");
          return;
        }
        // 新增要素
        const attachGroupId = uuidv4();
        const status = "1"
        // const length = _self.selectedGraphic.Shape__Length
        const attributes = {
          objcode: _self.formData.objcode,
          objectid: _self.formData.objectid,
          code: attachGroupId,
          name: _self.formData.name,
          roadclass_js: _self.formData.roadclass_js,
          ref_length: _self.formData.ref_length,
          // length: _self.formData.length,
          width: _self.formData.width,
          startpoint: _self.formData.startpoint,
          endpoint: _self.formData.endpoint,
          pavementmaterials: _self.formData.pavementmaterials,
          cleancompany: _self.formData.cleancompany,
          oldname: _self.formData.oldname,
          roadnumber: _self.formData.roadnumber,
          note: _self.formData.note,
          data_status: status,
          lanenumber:_self.formData.lanenumber,
          feijdcds:_self.formData.feijdcds,
          sfsidewalk:_self.formData.sfsidewalk,
          managementunit:_self.formData.managementunit
        };
        const addFeature = new Graphic({
          geometry:
          _self.selectedGraphic == undefined
            ? ""
            : _self.selectedGraphic.geometry,
          attributes: attributes,
        });
        _self.featureLayer
          .applyEdits({
          addFeatures: [addFeature],
          })
          .then((editsResult) => {
          console.log(editsResult);
          const objectId = editsResult.addFeatureResults[0].objectId;
          console.log(objectId);
          _self.$message.success("新增成功");
          _self.cancel();
          });
      });
    },
    // 添加空间位置
    addGeometry() {
      let _self = this;
      _self.udpateGraphicsLayer = new GraphicsLayer({
        title: "道路中心线编辑图层",
      });
      _self.mapview.map.add(_self.udpateGraphicsLayer);
      _self.sketch = new Sketch({
        layer: _self.udpateGraphicsLayer,
        view: _self.mapview,
        // graphic will be selected as soon as it is created
        creationMode: "update",
      });
      // 设置绘图工具条显示要素
      _self.sketch.visibleElements = {
        createTools: {
          point: false,
          polyline: true,
          polygon: false,
          rectangle: false,
          circle: false,
        },
        selectionTools: {
          "lasso-selection": false,
          "rectangle-selection": false,
        },
        settingsMenu: false,
      };
      _self.sketch.create();
      _self.mapview.ui.add(_self.sketch, "top-right");
      _self.sketch.on("create", (event) => {
        if (event.state === "complete") {
          console.log("create complete");
          _self.selectedGraphic = event.graphic;
          _self.addGraphics.push(event.graphic);
          // 每个要素只有一条线，如果已创建的一条线，则不允许继续创建点。隐藏创建线按钮
          if (_self.addGraphics.length > 0)
            document.getElementsByClassName(
              "esri-sketch__section esri-sketch__tool-section"
            )[1].style.display = "none";
          // _self.mapview.graphics.add(event.graphic);
          // _self.mapview.ui.remove(_self.sketch);
        }
      });
      _self.sketch.on("update", (event) => {
        if (event.state === "complete") {
          console.log("update complete");
          if (event.graphics.length == 0) return;
          _self.selectedGraphic = event.graphics[0];
        }
      });
      _self.sketch.on("delete", (event) => {
        event.graphics.forEach((graphic) => {
          console.log("deleted", graphic);
          if (graphic == _self.selectedGraphic)
            _self.selectedGraphic = undefined;
          _self.addGraphics = _self.addGraphics.filter(
            (item) => item !== graphic
          );
        });
        // 如果没有添加任何点，就显示创建点按钮
        if (_self.addGraphics.length == 0)
          document.getElementsByClassName(
            "esri-sketch__section esri-sketch__tool-section"
          )[1].style.display = "";
      });
    },
    resetForm() {
      let _self = this;
      _self.$refs["elForm"].resetFields();
    },
    clearGraphics(){
      let _self = this
      _self.addGraphics = [];
      // 删除临时图形
      if (_self.selectedGraphic)
        _self.udpateGraphicsLayer.remove(_self.selectedGraphic);
      _self.mapview.graphics.removeAll();
      _self.mapview.map.layers.remove(_self.udpateGraphicsLayer);
      // 删除微件
      _self.mapview.ui.remove(_self.sketch);
      },
    clearData(){
      let _self = this
      // 重置输入表单
      _self.$refs["elForm"].resetFields();
      // _self.formData = undefined;
      _self.featureLayer = undefined;
    },
    cancel() {
      let _self = this;
      _self.clearGraphics();
      _self.clearData();
      this.toggleComponent("dataPanel");
    },

  }
}
</script>

<style lang="scss" scoped>
.footer {
  margin-bottom: 1vh;
  display: flex;
  justify-content: center;
}
</style>
